package club.zhilin.guli.service.cms.controller.backend;

import club.zhilin.guli.common.base.result.CommonResult;
import club.zhilin.guli.service.cms.domain.Ad;
import club.zhilin.guli.service.cms.domain.vo.AdVO;
import club.zhilin.guli.service.cms.service.IAdService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 广告推荐 前端控制器
 * </p>
 *
 * @author zhilin
 * @since 2022-02-22 16:00:09
 */
@RestController
@Api(value = "首页广告管理")
@RequestMapping("/admin/cms/ad")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AdController {

    public final IAdService iAdService;
    @Resource
    private RedisTemplate<String, Serializable> redisTemplate;

    @ApiOperation("通过id删除推荐")
    @DeleteMapping("/remove/{id}")
    public CommonResult<String> remove(@PathVariable String id) {
        iAdService.removeAdImageId(id);
        boolean result = iAdService.removeById(id);
        return result ? CommonResult.success("删除成功") : CommonResult.failed("数据不存在");
    }

    @ApiOperation("推荐分页列表")
    @GetMapping("/list/{page}/{limit}")
    public CommonResult<Map<String, Object>> listPage(@ApiParam(value = "当前页码", required = true) @PathVariable Long page,
                                                      @ApiParam(value = "每页记录数", required = true) @PathVariable Long limit) {

        IPage<AdVO> pageModel = iAdService.selectPage(page, limit);
        List<AdVO> records = pageModel.getRecords();
        long total = pageModel.getTotal();
        HashMap<String, Object> result = new HashMap<>(2);
        result.put("total", total);
        result.put("rows", records);
        return CommonResult.success(result);
    }

    @ApiOperation("保存推荐")
    @PostMapping("/save")
    public CommonResult<String> save(@RequestBody Ad ad) {
        boolean result = iAdService.save(ad);
        return result ? CommonResult.success("保存成功") : CommonResult.failed("保存失败");
    }

    @ApiOperation("更新推荐")
    @PutMapping("/update")
    public CommonResult<String> update(@RequestBody Ad ad) {
        boolean result = iAdService.updateById(ad);
        return result ? CommonResult.success("更新成功") : CommonResult.failed("更新失败");
    }

    @ApiOperation("根据id查询推荐")
    @GetMapping("/get/{id}")
    public CommonResult<Ad> getAdById(@PathVariable String id) {
        Ad ad = iAdService.getById(id);
        if (ad == null) {
            return CommonResult.failed("数据不存在");
        }
        return CommonResult.success(ad);
    }
}

